<?php

namespace App\Admin\Controllers;

use App\Config;
use App\Http\Controllers\Controller;
use Dcat\Admin\Form;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use App\Admin\Metrics\Examples;
use Dcat\Admin\Http\Controllers\Dashboard;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Row;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        return $content
            ->header('Dashboard')
            ->description('Description...')
            ->body(function (Row $row) {
                $row->column(6, function (Column $column) {
                    $column->row(Dashboard::title());
                    $column->row(new Examples\Tickets());
                });

                $row->column(6, function (Column $column) {
                    $column->row(function (Row $row) {
                        $row->column(6, new Examples\NewUsers());
                        $row->column(6, new Examples\NewDevices());
                    });

                    $column->row(new Examples\Sessions());
                    $column->row(new Examples\ProductOrders());
                });
            });

//        return $content
//            ->header('Advertise')
//            ->body($this->form());
    }

    private function form()
    {
        return Form::make(new Config(), function (Form $form) {
            $config = $this->getConfig();
            foreach ($config as $item){
                if ($item['k'] != 'times'){
                    $form->text($item['k'], $item['des'])->value($item['v'])->required();
                }else{
                    $form->datetime($item['k'], $item['des'])->value($item['v'])->format('HH:mm')->required();
                }
            }
            $form->disableHeader();
            $form->disableResetButton();
            $form->disableListButton();
            $form->disableCreatingCheck();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->action('config');
        });
    }

    /**
     * @return array
     */
    private function getConfig()
    {
        return Config::query()->select('k', 'v', 'des')->orderBy('sort')->get()->toArray();
    }


    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $data = $request->all();
        foreach ($data as $k => $datum){
            Config::query()->where('k', $k)->update([
                'v' => $datum
            ]);
        }
        $response['data'] = [
            'message' => '更新成功',
            'type' => 'success',
        ];
        $response['status'] = true;
        return response()->json($response);
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function show(){
        $config = $this->getConfig();
        if (!Cache::has('token')){
            $token = $this->getToken();
            Cache::put('token', $token, 60 * 30);
            sleep(2);
        }else{
            $token = Cache::get('token');
        }
        $config = array_column($config, 'v', 'k');
        try {
            $returnData = $this->getData($token);
        }catch (\Exception $exception){
            logger("获取数据异常" . $exception->getMessage());
        }
        $config['people_count'] = strval($returnData[0]['data'][0]['value'] ?? 0);
        return response()->json([
            'code' => 0,
            'data' => $config
        ]);
    }

    public function token()
    {
        return $this->getToken();
    }


    /**
     * @return mixed
     * @throws \Exception
     */
    private function getToken()
    {
        try {
            $params = [
                'appId' => \config('app.api_appid'),
                'appKey' => \config('app.api_appkey')
            ];
            $url = \config('app.api_url') . '/developer/token?' . http_build_query($params);
            $response = $this->postHttpContent($url);
            return $response['data'];
        }catch (\Exception $exception){
            throw new \Exception("token获取异常" . $exception->getMessage());
        }

    }

    private function getData($token)
    {
        $date = date('Y-m-d');
        try {
            $params = [
                'id' => \config('app.api_id'),
                'startDay' => $date,
                'endDay' => $date,
                'type' => 'device',
                'timeSlice' => 'day',
                'direction' => 'strand'
            ];
            $url = \config('app.api_url') . '/analysis/getdata';

            $response = $this->getHttpContent($url, $params, [
                'Authorization' => 'Bearer ' . $token
            ]);
            return $response['data'];
        }catch (\Exception $exception){
            throw new \Exception("data获取异常" . $exception->getMessage());
        }

    }

    /**
     * @param string $url
     * @param array $params
     * @return array|mixed
     * @throws \Exception
     */
    private function postHttpContent(string $url, array $params = [], $header = [])
    {

        $response = Http::withHeaders($header)->post($url, $params);
        if ($response->successful()) {
            // 处理请求成功的响应
            return $response->json();
        } else {
            throw new \Exception("api数据获取异常");
        }
    }

    /**
     * @param string $url
     * @param array $params
     * @param array $header
     * @return array|mixed
     * @throws \Exception
     */
    private function getHttpContent(string $url, array $params = [], array $header)
    {
        $response = Http::withHeaders($header)->get($url, $params);
        if ($response->successful()) {
            // 处理请求成功的响应
            return $response->json();
        } else {
            throw new \Exception("api数据获取异常");
        }
    }

    public function home()
    {
        return view('welcome');
    }
}
